﻿@using System.ComponentModel
@using System.Net.Http.Headers
@using AntDesign.TableModels

@page "/admin/articles"
@layout AdminLayout


@* 依赖注入 *@
@inject HttpClient Http
@inject IJSRuntime JSRuntime
@inject MessageService _message
@inject NavigationManager navigationManager



<PageTitle>文章列表</PageTitle>


@* 面包屑 *@
<Breadcrumb Style="margin: 16px 0;">
    <BreadcrumbItem>admin</BreadcrumbItem>
    <BreadcrumbItem>articlelist</BreadcrumbItem>
</Breadcrumb>
<Content Class="site-layout-background" Style=" padding: 0px; margin: 0; min-height: 280px;">

    <div>
        <p style="color: darkblue;margin-bottom: 10px;font-size: 16px;font-weight:400;">文章列表</p>
        @*添加按钮*@
        <NavLink href="/admin/articles/add">
            <Button Type="@ButtonType.Primary" Icon="@IconType.Outline.PlusSquare">添加文章</Button>
        </NavLink>

        @*显示表格*@
        <Table Bordered=@true TItem="ArticleDto" DataSource="@_articles" @bind-PageIndex="_pageIndex"
            @bind-PageSize="_pageSize" Total="_total" Loading="_loading" OnChange="HandleTableChange" RemoteDataSource
            style="margin-top: 10px;">

            <ChildContent>
                <Column @bind-Field="@context.Id" Width="50"></Column>
                <Column @bind-Field="@context.Title" Width="300" Ellipsis></Column>
                <Column @bind-Field="@context.Category" Width="150">@context.Category.Name</Column>
                <Column @bind-Field="@context.Created_at">
                    @Utils.UnixTimeStampToDateTime(context.Created_at).ToString("yyyy/MM/dd")</Column>
                <Column @bind-Field="@context.Updated_at">
                    @Utils.UnixTimeStampToDateTime(context.Updated_at).ToString("yyyy/MM/dd")</Column>

                <ActionColumn Title="操作">
                    <Space Size=@("middle")>
                        <SpaceItem>
                            <Button Type="@ButtonType.Primary" Icon="@IconType.Outline.Edit"
                                OnClick="()=>Edit(context.Id)">编辑</Button>
                        </SpaceItem>
                        <SpaceItem>
                            <Popconfirm Placement="@Placement.Top" Title="确定删除吗？" OkText="确定" CancelText="取消"
                                OnConfirm="()=>Confirm(context.Id)">
                                <Button Danger Icon="@IconType.Outline.Delete">删除</Button>
                            </Popconfirm>
                        </SpaceItem>
                    </Space>
                </ActionColumn>
            </ChildContent>

            <PaginationTemplate>
                <div style="display: flex; align-items: center; justify-content: flex-end;">
                    <Pagination Class="my-custom-pagination" Total="@_total" PageSize="_pageSize" Current="_pageIndex"
                        ShowSizeChanger="@true" OnChange="HandlePageChange" />
                </div>
            </PaginationTemplate>
        </Table>
    </div>

</Content>

<style>
    .my-custom-pagination {
        margin: 15px 0;
    }

    .my-custom-pagination .ant-pagination-item,
    .my-custom-pagination .ant-pagination-item-link {
        border-radius: 100%;
    }
</style>


@code {
    private bool _loading = false; //是否加载状态
    private int _pageIndex = 1; //当前页码
    private int _pageSize = 10; //页大小
    private int _total; //总记录数


    //接收后端数据
    List<ArticleDto> _articles = new List<ArticleDto>();


    public struct Category
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

    public class ArticleDto
    {
        [DisplayName("ID")]
        public int Id { get; set; }
        [DisplayName("标题")]
        public string Title { get; set; }
        public string Description { get; set; }
        public string Content { get; set; }
        [DisplayName("创建时间")]
        public int Created_at { get; set; }
        [DisplayName("更新时间")]
        public int Updated_at { get; set; }
        [DisplayName("分类")]
        public Category Category { get; set; }
    }

    public class Article
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public string Content { get; set; }
        public int Created_at { get; set; }
        public int Updated_at { get; set; }
    }


    /// <summary>
    /// 接收响应数据，List<T>
    /// </summary>
    public class RespData<T> where T : new()
    {
        public int Code { get; set; }
        public string Msg { get; set; }
        public List<T> Data { get; set; } = new List<T>();
        public int Total { get; set; }
    }

    /// <summary>
    /// 接收响应数据，T
    /// </summary>
    public class RespData2<T> where T : new()
    {
        public int Code { get; set; }
        public string Msg { get; set; }
        public T Data { get; set; } = new T();
    }


    /// <summary>
    /// 初始化加载
    /// </summary>
    /// <returns></returns>
    protected override async Task OnInitializedAsync()
    {
        //获取数据
        await GetData();
        await base.OnInitializedAsync();
    }


    /// <summary>
    /// 表格分页改变事件
    /// </summary>
    /// <param name="queryModel"></param>
    /// <returns></returns>
    async Task HandleTableChange(QueryModel<ArticleDto> queryModel)
    {
        _loading = true;

        var artRes = await
        Http.GetFromJsonAsync<RespData<ArticleDto>>($"/api/articles?page={queryModel.PageIndex}&perPage={queryModel.PageSize}");
        _articles = artRes.Data;

        _loading = false;
        _total = artRes.Total;
    }

    /// <summary>
    /// 自定义分页的改变事件
    /// </summary>
    /// <param name="args"></param>
    private async Task HandlePageChange(PaginationEventArgs args)
    {
        if (_pageIndex != args.Page)
        {
            _pageIndex = args.Page;
        }
        if (_pageSize != args.PageSize)
        {
            _pageSize = args.PageSize;
        }
    }


    /// <summary>
    /// 删除确认事件
    /// </summary>
    /// <param name="id"></param>
    private async Task Confirm(int id)
    {
        var requestMessage = new HttpRequestMessage()
        {
            Method = new HttpMethod("DELETE"),
            RequestUri = new Uri($"{Utils.BASE_URL}/api/article/{id}"),
        };

        // 获取浏览器localStorage存储的token
        LocalStorageHelper localStorageHelper = new LocalStorageHelper(JSRuntime);
        string token = await localStorageHelper.GetLocalStorage("token");

        // 判断是否有token
        if (!string.IsNullOrEmpty(token))
        {
            // 添加token到请求头
            requestMessage.Headers.Authorization = new AuthenticationHeaderValue(token);
            // 发出请求
            var response = await Http.SendAsync(requestMessage);

            // 读取响应并反序列化
            var resData = await response.Content.ReadFromJsonAsync<RespData2<Article>>();

            if (resData != null && resData.Code != 200) // 删除失败
            {
                _message.Error("文章删除失败");
                _message.Error(resData.Msg);
            }
            else
            {
                _message.Success("文章删除成功");
                // 刷新表格数据
                await GetData();
            }
        }
        else
        {
            _message.Info("未登录，请登录后再试");
            // 重定向到登录页
            navigationManager.NavigateTo("/admin/login", true);
        }
    }


    /// <summary>
    /// 编辑按钮事件
    /// </summary>
    /// <param name="id"></param>
    private void Edit(int id)
    {
        navigationManager.NavigateTo($"/admin/article/add/{id}");
    }


    /// <summary>
    /// 获取数据方法
    /// </summary>
    /// <returns></returns>
    private async Task GetData()
    {
        _loading = true;

        var artRes = await Http.GetFromJsonAsync<RespData<ArticleDto>>("/api/articles");
        if (artRes != null && artRes.Data != null)
        {
            _articles = artRes.Data;
        }

        _loading = false;
        _total = artRes.Total;
    }
}
